package com.LeeCode;

/**
 * 两数相加 II
 */

public class Code445 {
    public static void main(String[] args) {
        int[] arr1 = {7, 2, 4, 3};
        int[] arr2 = {5, 6, 4};
        ListNode l1 = Utils.arrayToListNode(arr1);
        ListNode l2 = Utils.arrayToListNode(arr2);
        Utils.printListNode(new Code445().addTwoNumbers(l1, l2));
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        l1 = reverse(l1);
        l2 = reverse(l2);
        l1 = addTwoNumbers1(l1, l2);
        return reverse(l1);
    }

    private ListNode reverse(ListNode head) {
        ListNode prev = null, cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    private ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode ans = l1;

        int carry = 0;
        while (l1 != null || l2 != null) {
            int v1 = l1 != null ? l1.val : 0;
            int v2 = l2 != null ? l2.val : 0;
            int tmp = v1 + v2 + carry;

            carry = tmp > 9 ? 1 : 0;
            //开辟额外内存
            // 1.有进位但l1没了
            if (carry > 0 && l1.next == null)
                l1.next = new ListNode(0);
            // 2.l1没了且没有进位 但是l2还有 这里要用短路与符号，不然最后一个判断式会报空指针异常
            if (l1.next == null && l2 != null && l2.next != null)
                l1.next = new ListNode(0);
            l1.val = tmp % 10;
            l1 = l1.next;
            if (l2 != null)
                l2 = l2.next;
        }
        return ans;
    }
}
